package linc.cool.framework;

import linc.cool.framework.register.RemoteMapRegister;
import org.apache.dubbo.common.utils.StringUtils;

import java.lang.reflect.Proxy;

/**
 * @author yqlin
 * @date 2022/3/11 2:56 下午
 * @description 用于获取远程调用方法所在的类
 */
public class ProxyFactory<T> {
    @SuppressWarnings("unchecked")
    public static <T> T getProxy(final Class<?> interfaceClass) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, (proxy, method, args) -> {
            try {
                // 获取协议
                Protocol protocol = ProtocolFactory.getProtocol();
                // 当服务还未实现完,所以没有必要去发送,可以进行mock逻辑
                String mock = System.getProperty("mock");
                if (!StringUtils.isBlank(mock) && "return:".startsWith(mock)) {
                    return mock.replace("return:", "");
                }
                // 代理逻辑
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
                var urlList = RemoteMapRegister.get(interfaceClass.getName());
                // 负载均衡
                URL url = LoadBalance.random(urlList);
                return protocol.send(url, invocation);
            } catch (Exception e) {
                e.printStackTrace();
                // 容错
                return "服务正忙,稍后再试";
            }
        });
    }
}
